package com.example.ibsp_demo.service.impl;

import com.example.ibsp_demo.mapper.login.VerificationCodeMapper;
import com.example.ibsp_demo.pojo.entity.login.VerificationCode;

import com.example.ibsp_demo.service.IVerificationCodeService;
import com.example.ibsp_demo.service.email.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Random;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    @Autowired
    private VerificationCodeMapper codeMapper;

    @Autowired
    private EmailService emailService;

    // 验证码有效期（分钟）
    private static final int EXPIRE_MINUTES = 3;//因为验证码按钮就是间隔一分钟才能按一次

    // 验证码长度
    private static final int CODE_LENGTH = 6;

    @Override
    public String sendCode(String target, String type) {
        // 1. 检查是否已有未过期的同类型验证码（避免频繁发送）
        VerificationCode existingCode = codeMapper.selectValidCode(
                target,
                type,
                0,  // 未使用
                LocalDateTime.now()
        );
        if (existingCode != null) {
            throw new RuntimeException("验证码已发送，请勿频繁请求（有效期" + EXPIRE_MINUTES + "分钟）");
        }

        // 2. 生成随机验证码
        String code = generateRandomCode();

        // 3. 构建验证码实体
        VerificationCode verificationCode = new VerificationCode();
        verificationCode.setTarget(target);
        verificationCode.setCode(code);
        verificationCode.setType(type);
        verificationCode.setCreateTime(LocalDateTime.now());
        verificationCode.setExpireTime(LocalDateTime.now().plusMinutes(EXPIRE_MINUTES));
        verificationCode.setIsUsed(0);  // 0-未使用

        // 4. 存入数据库
        codeMapper.insert(verificationCode);

        // 5. 发送邮件（根据类型决定邮件内容）
        sendVerificationEmail(target, type, code);
        return code;
    }

    @Override
    public boolean verifyCode(String target, String type, String code) {
        // 1. 查询有效的验证码
        VerificationCode validCode = codeMapper.selectValidCode(
                target,
                type,
                0,  // 未使用
                LocalDateTime.now()
        );

        // 2. 验证验证码是否存在且匹配
        if (validCode == null || !validCode.getCode().equals(code)) {
            return false;
        }

        // 3. 验证通过，标记为已使用
        validCode.setIsUsed(1);
        codeMapper.update(validCode);

        return true;
    }
    @Override
    public String sendVerificationCode(String email,String typeCode) {
       return sendCode(email, typeCode);
    }

    // 生成随机验证码
    private String generateRandomCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    // 发送验证邮件
    private void sendVerificationEmail(String target, String type, String code) {
        String subject = "";
        String content = "";

        // 根据不同类型生成不同的邮件内容
        if ("register".equals(type)) {
            subject = "【兴趣社交平台】注册验证码";
            content = "您的注册验证码是：" + code + "，有效期" + EXPIRE_MINUTES + "分钟。";
        } else if ("reset_password".equals(type)) {
            subject = "【兴趣社交平台】重置密码验证码";
            content = "您的重置密码验证码是：" + code + "，有效期" + EXPIRE_MINUTES + "分钟。";
        } else {
            subject = "【兴趣社交平台】验证码";
            content = "您的验证码是：" + code + "，有效期" + EXPIRE_MINUTES + "分钟。";
        }

        emailService.sendSimpleMail(target, subject, content);
    }
}
